/**
 * 游戏记录相关API服务
 */

import api, { getAuthHeaders } from './api';

export interface GameScore {
  id: number;
  score: number;
  correct_count: number;
  wrong_count: number;
  combo_max: number;
  accuracy: number;
  wpm: number;
  duration: number;
  case_sensitive: boolean;
  created_at: string;
}

export interface SubmitScoreRequest {
  score: number;
  correctCount: number;
  wrongCount: number;
  comboMax: number;
  accuracy: number;
  wpm: number;
  duration: number;
  caseSensitive?: boolean;
}

export interface ScoresResponse {
  total: number;
  page: number;
  limit: number;
  data: GameScore[];
}

export class GameScoresService {
  /**
   * 提交游戏分数
   */
  static async submitScore(data: SubmitScoreRequest): Promise<{ message: string; recordId: number }> {
    const response = await fetch(`${api.baseURL}/game-scores`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders(),
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '提交分数失败');
    }

    return response.json();
  }

  /**
   * 获取用户游戏记录列表
   */
  static async getScores(page: number = 1, limit: number = 20): Promise<ScoresResponse> {
    const response = await fetch(`${api.baseURL}/game-scores?page=${page}&limit=${limit}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders(),
      },
    });

    if (!response.ok) {
      throw new Error('获取游戏记录失败');
    }

    return response.json();
  }

  /**
   * 获取用户最佳记录
   */
  static async getBestScore(): Promise<GameScore> {
    const response = await fetch(`${api.baseURL}/game-scores/best`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders(),
      },
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取最佳记录失败');
    }

    return response.json();
  }

  /**
   * 删除游戏记录
   */
  static async deleteScore(id: number): Promise<{ message: string }> {
    const response = await fetch(`${api.baseURL}/game-scores/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders(),
      },
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '删除记录失败');
    }

    return response.json();
  }
}
